package extractor;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageExtractor {
	private Pattern patternTag, patternSrc, patternAlt;
	private Matcher matcherTag, matcherSrc, matcherAlt;

	private static final String HTML_TAG_PATTERN = "(?i)<img([^>]+)/>";
	private static final String HTML_SRC_PATTERN = "\\s*(?i)src\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))";
	private static final String HTML_ALT_PATTERN = "\\s*(?i)alt\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))";

	public ImageExtractor() {
		patternTag = Pattern.compile(HTML_TAG_PATTERN);
		patternSrc = Pattern.compile(HTML_SRC_PATTERN);
		patternAlt = Pattern.compile(HTML_ALT_PATTERN);
	}

	public Vector<HtmlImage> grabImages(String html) {

		Vector<HtmlImage> result = new Vector<HtmlImage>();

		matcherTag = patternTag.matcher(html);

		while (matcherTag.find()) {

			String tag = matcherTag.group(1);

			String image = null;
			matcherSrc = patternSrc.matcher(tag);
			if (matcherSrc.find()) {
				image = matcherSrc.group(1);
				if (image.startsWith("\""))
					image = image.substring(1, image.length() - 1);
			}

			String alt = null;
			matcherAlt = patternAlt.matcher(tag);
			if (matcherAlt.find()) {
				alt = matcherAlt.group(1);
			}

			// System.out.println("---> IMAGE: src = " + image + ", alt = " +
			// alt);
			HtmlImage i = new HtmlImage(image, alt);
		}

		return result;

	}

	public static class HtmlImage {
		public String image;
		public String alt;

		HtmlImage(String image, String alt) {
			this.image = image.trim().toLowerCase();
			if (alt != null)
				this.alt = alt.trim().toLowerCase();
		}
	}
}
